package com.andox.fn.inf.rpc.rest.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.andox.fn.inf.rpc.rest.RequestContext;
import com.andox.fn.inf.rpc.rest.RequestContextConstants;
import com.andox.fn.inf.rpc.rest.RpcRequest;
import com.andox.fn.inf.rpc.rest.common.RequestType;
import com.andox.fn.inf.rpc.rest.extension.ExtensionLoader;
import com.andox.fn.inf.rpc.rest.filter.Invoker;
import com.andox.fn.inf.rpc.rest.serializer.Serializer;


/**   
 * @ClassName:   InvokerInvocationHandler   
 * @Description: TODO  
 * @author:      Andox
 * @date:        2019年8月5日 上午9:35:48   
 *     
 */
public class InvokerInvocationHandler implements InvocationHandler {

	private Invoker invoker;
	private Serializer serializer;
	public InvokerInvocationHandler(Invoker invoker) {
		this.invoker = invoker;
		serializer = ExtensionLoader.getExtensionLoader(Serializer.class).getExtension(invoker.getConfig().getSerialization());
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		RpcRequest req = RpcRequest.newInstanceWithId();
		
		req.setMethod(method.getName());
		req.setType(RequestType.BIZ_BEAT);
		
		RequestContext.instance().reset();
		RequestContext.instance().putProperty(RequestContextConstants.REQUEST_PARAM, args);
		RequestContext.instance().putProperty(RequestContextConstants.REQUEST_PARAM_TYPE, method.getParameterTypes());
		RequestContext.instance().putProperty(RequestContextConstants.JAVA_METHOD, method);
		
		return invoker.invoke(req).recreate(this.serializer);
	}

}
